package com.holyn.guofang.view.my;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.LogItemWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.my.MyContract;
import com.holyn.guofang.presenter.my.MyPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.vondear.rxtools.RxTimeUtils;
import com.vondear.rxtools.view.dialog.RxDialogWheelYearMonthDay;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/8/22.
 */

public class MyLogActivity extends BaseActivity implements BaseView, MyContract.UserLogListView, OnLoadmoreListener {
    private static final int REQUEST_ACTION_POST_USER_LOG_LIST_FIRST = 0x0001;
    private static final int REQUEST_ACTION_POST_USER_LOG_LIST_MORE = 0x0002;

    @BindView(R.id.tv_begin_date)
    TextView tvBeginDate;
    @BindView(R.id.ll_begin_date)
    LinearLayout llBeginDate;
    @BindView(R.id.tv_end_date)
    TextView tvEndDate;
    @BindView(R.id.ll_end_date)
    LinearLayout llEndDate;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    MyContract.Presenter presenter;

    private RxDialogWheelYearMonthDay mRxDialogWheelYearMonthDay;
    private int curDataSelectType = 1;//1代表选择开始时间，2代表选择结束时间

    String from;
    String to;
    Integer pageSize = 12;
    Integer page = 1;

    MyRecyclerAdapter adapter;
    List<LogItemWo.DataBean> logList = new ArrayList<>();

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_my_log;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("使用日志");

        presenter = new MyPresenter(this);
        presenter.addUserLogListView(this);

        to = RxTimeUtils.getCurrentDateTime("yyyy-MM-dd");
        from = get3MonthAgo(to);
        tvBeginDate.setText(from);
        tvEndDate.setText(to);

        presenter.postUserLogList(REQUEST_ACTION_POST_USER_LOG_LIST_FIRST, from, to, pageSize, page);

        initRefreshLayout();
        initRecyclerView();

        initWheelYearMonthDayDialog();

    }

    private void initRefreshLayout(){
        refreshLayout.setOnLoadmoreListener(this);
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                ClassicsFooter footer = new ClassicsFooter(context);
                footer.setBackgroundResource(android.R.color.white);
                footer.setSpinnerStyle(SpinnerStyle.Scale);//设置为拉伸模式
                return footer;//指定为经典Footer，默认是 BallPulseFooter
            }
        });
    }

    private void initRecyclerView(){
        adapter = new MyRecyclerAdapter(logList);
        rvList.setLayoutManager(new LinearLayoutManager(MyLogActivity.this));
        rvList.setAdapter(adapter);

    }

    @OnClick({R.id.ll_begin_date, R.id.ll_end_date, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_begin_date:
                curDataSelectType = 1;
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.ll_end_date:
                curDataSelectType = 2;
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.btn_search:
                if (isDateFromLessDateTo()){
                    page = 1;
                    presenter.postUserLogList(REQUEST_ACTION_POST_USER_LOG_LIST_FIRST, from, to, pageSize, page);
                } else {
                    toastMsg("开始时间不能大于结束时间");
                }
                break;
        }
    }

    private boolean isDateFromLessDateTo(){
        long fromL = RxTimeUtils.string2Milliseconds(from);
        long toL = RxTimeUtils.string2Milliseconds(to);
        if (fromL <= toL){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onLoadmore(RefreshLayout refreshLayout) {
        page++;
        presenter.postUserLogList(REQUEST_ACTION_POST_USER_LOG_LIST_MORE, from, to, pageSize, page);
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
        refreshLayout.finishLoadmore();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
        refreshLayout.finishLoadmore();
    }

    @Override
    public void responseSuccess(int requestAction, LogItemWo logItemWo) {
        if (logItemWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<LogItemWo.DataBean> data = logItemWo.getData();
            if (data != null){
                if (requestAction == REQUEST_ACTION_POST_USER_LOG_LIST_FIRST){
                    logList.clear();
                    logList.addAll(data);
                } else if (requestAction == REQUEST_ACTION_POST_USER_LOG_LIST_MORE){
                    logList.addAll(data);
                }
                adapter.notifyDataSetChanged();
            }
        } else {
            toastMsg("获取数据失败");
        }
    }

    public String get3MonthAgo(String time){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        long month3AgoMilliseconds = RxTimeUtils.string2Milliseconds(time, format) - 92L*86400000L;
        return RxTimeUtils.milliseconds2String(month3AgoMilliseconds, format);
    }

    private void initWheelYearMonthDayDialog() {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDay(this, 2000, 2100);
        mRxDialogWheelYearMonthDay.getCheckBox_day().setVisibility(View.GONE);
        mRxDialogWheelYearMonthDay.getYear().setCurrentItem(17);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        int year = mRxDialogWheelYearMonthDay.getSelectorYear();
                        String month = mRxDialogWheelYearMonthDay.getSelectorMonth();
                        String day = mRxDialogWheelYearMonthDay.getSelectorDay();
                        String date = year + "-" + month + "-" +day;
                        if (curDataSelectType == 1){
                            from = date;
                            tvBeginDate.setText(date);
                        } else if (curDataSelectType == 2){
                            to = date;
                            tvEndDate.setText(date);
                        }
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

    private class MyRecyclerAdapter extends BaseQuickAdapter<LogItemWo.DataBean, BaseViewHolder>{

        public MyRecyclerAdapter(@Nullable List<LogItemWo.DataBean> data) {
            super(R.layout.item_my_log, data);
            addHeardView();
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, LogItemWo.DataBean dataBean) {
            baseViewHolder.setText(R.id.tv_position, String.valueOf(baseViewHolder.getAdapterPosition()+1));
            baseViewHolder.setText(R.id.tv_add_time, dataBean.getAddTime());
            baseViewHolder.setText(R.id.tv_equipment_code, dataBean.getEquipmentCode());
            baseViewHolder.setText(R.id.tv_describe, dataBean.getDescribe());
        }

        private void addHeardView(){
            View heardView = LayoutInflater.from(MyLogActivity.this).inflate(R.layout.heard_my_log, null);
            addHeaderView(heardView);
        }
    }
}
